package cn.edu.scau.cmi.ema.service;

import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;


import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.persistence.Query;
import java.util.Iterator;
@Service("DetectfeatureService")
@Transactional

public class DetectfeatureServiceImpl extends CmiEmaService implements DetectfeatureService {
	public DetectfeatureServiceImpl() {
	}

	@Transactional
	public Detectfeature saveDetectfeature(Detectfeature detectfeature) {

		if (detectfeature.getId() == null) {
			Detect detect = detectDAO.findDetectById(detectfeature.getDetect().getId());
			Feature feature = featureDAO.findFeatureById(detectfeature.getFeature().getId());
			Unit unit = unitDAO.findUnitById(detectfeature.getUnit().getId());

			Detectfeature existingDetectfeature = detectfeatureDAO.findDetectfeatureByPhysicalPrimaryKey(detect.getId(),
					feature.getId());

			detectfeature.setDetect(detect);
			detectfeature.setFeature(feature);
			detectfeature.setUnit(unit);

			if (isEquals(detectfeature, existingDetectfeature)) {
				return existingDetectfeature;
			}

			detectfeature = detectfeatureDAO.store(detectfeature);
			detectfeatureDAO.flush();

		} else {
			Detectfeature existingDetectfeature = detectfeatureDAO.findDetectfeatureByPrimaryKey(detectfeature.getId());

			detectfeature = detectfeatureDAO.store(detectfeature);
			detectfeatureDAO.flush();
		}

		return detectfeature;
	}

	public void deleteDetectfeature(Detectfeature detectfeature) {
		detectfeatureDAO.remove(detectfeature);
		detectfeatureDAO.flush();
	}

	@Transactional
	public void deleteDetectfeatures(Set<Integer> deleteDetectfeaturesId) {
		Query query = detectfeatureDAO.createNamedQuery("deleteDetectfeaturesById", -1, -1);
		query.setParameter(1, deleteDetectfeaturesId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Detectfeature> loadDetectfeatures() {
		return detectfeatureDAO.findAllDetectfeatures();

	}

	@Transactional
	public Set<Detectfeature> loadReferenceDetectfeatures(Set<Detectfeature> detectfeatures) {
		Iterator<Detectfeature> detectfeaturesIterator = detectfeatures.iterator();
		Set<Detectfeature> referencedDetectfeatures = new HashSet<>();
		while (detectfeaturesIterator.hasNext()) {
			Detectfeature currentDetectfeature = detectfeaturesIterator.next();

		}
		return referencedDetectfeatures;
	}

	public Set<Detectfeature> loadDetectfeaturesByIdSet(Set<Integer> detectfeatureIdSet) {

		Iterator<Integer> detectfeatureIdIterator = detectfeatureIdSet.iterator();
		Set<Detectfeature> detectfeatureSet = new HashSet<>();
		while (detectfeatureIdIterator.hasNext()) {
			Integer id = detectfeatureIdIterator.next();
			Detectfeature currentDetectfeature = detectfeatureDAO.findDetectfeatureById(id);
			detectfeatureSet.add(currentDetectfeature);
		}
		return detectfeatureSet;
	}

	@Transactional
	public List<Detectfeature> findAllDetectfeatures(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Detectfeature>(detectfeatureDAO.findAllDetectfeatures(startResult, maxRows));
	}

	@Transactional
	public Detectfeature findDetectfeatureByPrimaryKey(Integer id) {
		return detectfeatureDAO.findDetectfeatureByPrimaryKey(id);
	}

	@Transactional
	public Integer countDetectfeatures() {
		return ((Long) detectfeatureDAO.createQuerySingleResult("select count(o) from Detectfeature o")
				.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countDetectfeatures(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Detectfeature.class);
		return ((Long) detectfeatureDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 * 
	 */
	@Transactional
	public Integer countDetectfeaturesByName(String queryName) {
		Query query = detectfeatureDAO.createNamedQuery("countDetectfeaturesByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countDetectfeaturesByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Detectfeature.class);
		Session session = entityManager.unwrap(Session.class);
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadDetectfeatureObjectReferencedSet(Detectfeature detectfeature) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();
		if (detectfeature.getDetect() != null) {

			Set<Integer> detectIds = new HashSet<Integer>();
			detectIds.add(detectfeature.getDetect().getId());
			objectReferencedSetMap.put("detectIds", detectIds);
		}
		if (detectfeature.getFeature() != null) {

			Set<Integer> featureIds = new HashSet<Integer>();
			featureIds.add(detectfeature.getFeature().getId());
			objectReferencedSetMap.put("featureIds", featureIds);
		}
		if (detectfeature.getUnit() != null) {

			Set<Integer> unitIds = new HashSet<Integer>();
			unitIds.add(detectfeature.getUnit().getId());
			objectReferencedSetMap.put("unitIds", unitIds);
		}

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadDetectfeatureClassReferencedSet(Detectfeature detectfeature) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("detects", detectDAO.findAllDetects());
		classReferencedSetMap.put("features", featureDAO.findAllFeatures());
		classReferencedSetMap.put("units", unitDAO.findAllUnits());

		return classReferencedSetMap;
	}

	public boolean isEquals(Detectfeature detectfeature, Object obj) {
		if (obj == detectfeature)
			return true;
		if (!(obj instanceof Detectfeature))
			return false;
		Detectfeature comparedDetectfeature = (Detectfeature) obj;
		if (!CheckPropertyEqual(detectfeature.getDetect().getId(), comparedDetectfeature.getDetect().getId())) {
			return false;
		}
		if (!CheckPropertyEqual(detectfeature.getFeature().getId(), comparedDetectfeature.getFeature().getId())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

